#! /usr/bin/python
# -*- coding:  utf-8 -*-
#
# accoufer : cgi script for  requesting offers from a server
# 
# Copyright S.Keim 2011
# Available under the MIT licence see the COPYING file


import accoufer
import shelve
import cgi 
import urllib2, urllib,math


def run():
    class param:
        table = ""
        server = ""
    # extract parameters
    form = cgi.FieldStorage()
    try:
        param.ref = form["ref"].value
    except KeyError:
        return fatal_error("Invalid request")
    
    offers = shelve.open(accoufer.offerpath(param.ref), 'r')
    param.url = offers[accoufer.URL_KEY]
    param.name = offers[accoufer.NAME_KEY]
    
    data = urllib.urlencode({"client":accoufer.SERVICE_URL})
    try:
        f = accoufer.urlopen(param.url+"/offers", data=data) 
    except IOError:
        return error(param,  "Unable to contact server")
    rows = []
    if f.next() != "OK\n":
        code = f.next()
        return error(param,  f.next())
       
    emails = shelve.open(accoufer.EMAIL_PATH, "r")      
    for l in f:
        l = l.strip()
        if not l:
            continue
        l =l.split(',')
        oref, svalue, min_svalue, tx, email = l
        
        if email not in emails:
            continue
        # todo check email != user.email, min, max ...
        
        tx = float(tx)
        cvalue = math.ceil(tx*float(svalue))
        min_cvalue = math.ceil(tx*float(min_svalue))

      
        respond = "./xrespond?oref=%s&sref=%s&tx=%s"%(oref,param.ref,tx)
        
        r = """<tr><td>%.2f</td> <td>+%s</td> <td>+%s</td> <td>-%s</td><td>-%s</td><td><a href=%s><img src="../basket.png" title="xrespond"</a></td></tr>"""%(tx, min_svalue, svalue, min_cvalue, cvalue, respond)
        rows.append( (tx, r) )
    rows.sort()
    rows.reverse()
    rows = [x[1] for x in rows]
    param.table = "\n".join(rows)
    print accoufer.HTML%( "Proposals: "+param.name, FORM%param.__dict__ )    

def fatal_error(txt):
    print accoufer.HTML%("Fatal error", txt)
        
def error(param, txt):
    param.err = txt
    msg = ERROR%param.__dict__
    print accoufer.HTML%("Error", msg)
    
FORM = """<h1>Proposals: %(name)s</h1>
<table>
<tr><th></th><th colspan=2>On service</th><th colspan=2>Here</th><th></th>
<tr><th>rate</th><th>min</th><th>value</th><th>min</th><th>value</th><th> .</th> </tr>
%(table)s
</table>
<hr/><a href="./index.html">Start</a> 
"""

ERROR = """<h1>Error</h1><b>%(err)s</b><hr/><a href="./index.html">Start</a>"""



if __name__=="__main__":
    run()
